package com.rq.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Stack;

public class JavaCodeFinder {

    public static void main(String[] args) {
        searchConInJavaFile("E:\\AndroidCode", "NestingViewHolder");
    }

    public static void searchConInJavaFile(String foldPath, String searchKey) {
        File rootFolder = Paths.get(foldPath).toFile();
        Stack<File> stack = new Stack<>();
        stack.push(rootFolder);
        int hasFindSize = 0;
        while (!stack.isEmpty()) {
            File folder = stack.pop();
            if (folder.isDirectory()) {
                File[] files = folder.listFiles();
                if (files != null) {
                    for (File file : files) {
                        stack.push(file);
                    }
                }
//                String path = folder.getAbsolutePath();
//                if (path.contains("\\java\\") && folder.list() != null && folder.list().length > 0) {
//                    System.out.println(path);
//                }
            } else {
                String path = folder.getAbsolutePath();
                // 处理文件
                if (path.endsWith(".java") && !path.contains("\\build\\")) {
//                    String printPath = path.replace(rootFolder.getAbsolutePath(), "\t");
//                    printPath = printPath.replaceAll(".*?\\\\", "\t");
                    if (hasContent(path, searchKey)) {
                        hasFindSize++;
                        System.out.println("has." + searchKey + ":" + path);
                    } else {
                        System.out.print(".");
                    }
                }
//                System.out.println(path);
            }
        }
        if (hasFindSize == 0) {
            System.out.println("not find " + searchKey + " in " + foldPath);
        } else {
            System.out.println("find " + hasFindSize + " usages in " + foldPath);
        }
    }

    public static boolean hasContent(String fileName, String searchContent) {
        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains(searchContent)) {
                    return true;
                }
//                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
